<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <employee-search :where="defaultWhere" @search="reload" />
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="userId"
        :columns="columns"
        :datasource="datasource"
        v-model:selection="selection"
        :scroll="{ x: 1000 }"
        :where="defaultWhere"
        cache-key="proSystemUserTable"
      >
        <template #toolbar>
          <a-space>
            <a-button type="primary" class="ele-btn-icon" @click="openEdit()">
              <template #icon>
                <plus-outlined />
              </template>
              <span>新建</span>
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <!-- 头像列 -->
          <template v-if="column.key === 'headImg'">
            <a-avatar
              v-if="record.headImg"
              :src="API_BASE_URL + 'img?name=' + record.headImg"
              :size="50"
              @click.stop=""
            />
            <a-avatar v-else class="ele-bg-primary" :size="32" @click.stop="">
              {{
                record.name && record.name.length > 2
                  ? record.name.substring(record.name.length - 2)
                  : record.name
              }}
            </a-avatar>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-switch
              :checked="record.status === true"
              @change="(checked: boolean) => editStatus(checked, record)"
            />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="openEdit(record)">修改</a>
              <a-divider type="vertical" />
              <a @click="resetPsw(record)">重置密码</a>
              <a-divider type="vertical" />
              <!-- <a-popconfirm
                placement="topRight"
                title="确定要删除此用户吗？"
                @confirm="remove(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm> -->
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <employee-edit v-model:visible="showEdit" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, createVNode } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import { EleProTable, messageLoading } from 'ele-admin-pro/es';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString } from 'ele-admin-pro/es';
  import employeeSearch from './components/employee-search.vue';
  import employeeEdit from './components/employee-edit.vue';
  import {
    updateEmployeeStatus,
    getEmployeeList,
    updateEmployeePassword
  } from '@/api/employee';
  import { Employee, EmployeeParam } from '@/api/employee/model';
  import { API_BASE_URL } from '@/config/setting';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      width: 80,
      title: '头像',
      key: 'headImg',
      dataIndex: 'headImg',
      ellipsis: true,
      align: 'center'
    },
    {
      title: '用户账号',
      dataIndex: 'account',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '用户名',
      key: 'name',
      dataIndex: 'name',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '超级管理员',
      dataIndex: 'supper',
      sorter: true,
      showSorterTooltip: false,
      customRender: ({ text }) => (text ? '是' : '否')
    },
    {
      title: '登录次数',
      dataIndex: 'count',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      sorter: true,
      showSorterTooltip: false,
      width: 90,
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center'
    }
  ]);

  // 表格选中数据
  const selection = ref<Employee[]>([]);

  // 当前编辑数据
  const current = ref<Employee | null>(null);

  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 默认搜索条件
  const defaultWhere = reactive({
    account: ''
  });

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    const index = page;
    const size = limit;
    return getEmployeeList({ ...where, ...orders, index, size });
  };

  /* 搜索 */
  const reload = (where?: EmployeeParam) => {
    selection.value = [];
    tableRef?.value?.reload({ page: 1, where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: Employee) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 重置用户密码 */
  const resetPsw = (row: Employee) => {
    Modal.confirm({
      title: '提示',
      content: '确定要重置此用户的密码为"123456"吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = messageLoading('请求中..', 0);
        updateEmployeePassword({
          id: row.id,
          name: row.name,
          status: row.status,
          password: '123456',
          remark: row.remark
        })
          .then((msg) => {
            hide();
            message.success(msg);
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 修改用户状态 */
  const editStatus = (checked: boolean, row: Employee) => {
    updateEmployeeStatus(row.id, checked)
      .then(() => {
        row.status = checked;
        if (checked) {
          message.success('已启用');
        } else {
          message.error('已禁用');
        }
      })
      .catch((e) => {
        message.error(e.message);
      });
  };
</script>

<script lang="ts">
  export default {
    name: 'SystemUser'
  };
</script>
